<template>
  <!-- 模态窗口模式 -->
  <div class="sql-to-markdown-modal" v-if="isModal && visible" @click.self="closeModal">
    <div class="sql-to-markdown-container">
      <div class="modal-header">
        <h2>SQL转Markdown工具</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>

      <div class="modal-content">
        <div class="form-group">
          <label>SQL输入：</label>
          <textarea
            v-model="sqlInput"
            class="sql-input"
            placeholder="请输入CREATE TABLE SQL语句..."
            rows="10"
          ></textarea>
        </div>

        <div class="buttons">
          <button class="convert-btn" @click="convertToMarkdown">转换为标准格式</button>
          <button class="convert-btn custom" @click="convertToCustomFormat">
            转换为自定义格式
          </button>
          <button class="clear-btn" @click="clearAll">清空</button>
        </div>

        <div class="result-section" v-if="markdownResult">
          <h3>Markdown结果：</h3>
          <div class="preview-section">
            <h4>预览：</h4>
            <div class="markdown-preview" v-html="renderMarkdown"></div>
          </div>

          <div class="code-section">
            <h4>Markdown代码：</h4>
            <textarea
              v-model="markdownResult"
              class="markdown-output"
              readonly
              rows="15"
            ></textarea>
            <button class="copy-btn" @click="copyToClipboard">复制到剪贴板</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 普通页面模式 -->
  <div v-if="!isModal" class="sql-to-markdown-page">
    <div class="sql-to-markdown-content">
      <h2>SQL转Markdown工具</h2>

      <div class="form-group">
        <label>SQL输入：</label>
        <textarea
          v-model="sqlInput"
          class="sql-input"
          placeholder="请输入CREATE TABLE SQL语句..."
          rows="10"
        ></textarea>
      </div>

      <div class="buttons">
        <button class="convert-btn" @click="convertToMarkdown">转换为标准格式</button>
        <button class="convert-btn custom" @click="convertToCustomFormat">转换为自定义格式</button>
        <button class="clear-btn" @click="clearAll">清空</button>
      </div>

      <div class="result-section" v-if="markdownResult">
        <h3>Markdown结果：</h3>
        <div class="preview-section">
          <h4>预览：</h4>
          <div class="markdown-preview" v-html="renderMarkdown"></div>
        </div>

        <div class="code-section">
          <h4>Markdown代码：</h4>
          <textarea v-model="markdownResult" class="markdown-output" readonly rows="15"></textarea>
          <button class="copy-btn" @click="copyToClipboard">复制到剪贴板</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineExpose, defineProps, withDefaults } from 'vue'
import { SqlToMarkdown } from './SqlToMarkdown'
import { ElMessage } from 'element-plus'

// 定义属性
const props = withDefaults(
  defineProps<{
    isModal?: boolean // 是否为模态窗口模式
  }>(),
  {
    isModal: false, // 默认为普通页面模式
  },
)

const visible = ref(false)
const sqlInput = ref<string>(`create table t_voucher_header
(
    id                         bigint unsigned auto_increment comment '主键id'
        primary key,
    year                       varchar(4)     default ''     not null comment '会计年度',
    pk_system                  varchar(20)    default 'GL'   not null comment '来源系统',
    pk_accountingbook          varchar(30)    default ''     not null comment '核算账簿',
    discardflag                varchar(1)     default 'N'    null comment '作废标志',
    period varchar (4) default '' not null comment '会计期间 需根据当前会计月度填写',
    attachment                 int            default 0      null comment '附单据数',
    prepareddate               datetime                      null comment '制单日期',
    pk_prepared                varchar(30)    default ''     null comment '制单人（用户）采用固定值'
)
    comment '凭证抬头' charset = utf8;`)

const markdownResult = ref<string>('')

// 打开模态窗口
const openModal = () => {
  visible.value = true
  // 当打开模态窗时，阻止背景页面滚动
  document.body.style.overflow = 'hidden'
}

// 关闭模态窗口
const closeModal = () => {
  visible.value = false
  // 当关闭模态窗时，恢复背景页面滚动
  document.body.style.overflow = ''
}

// 简单的Markdown渲染函数
const renderMarkdown = computed(() => {
  if (!markdownResult.value) return ''

  let html = markdownResult.value
    // 替换表格头部和分隔行
    .replace(
      /\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|\n\|([-\s]*)\|([-\s]*)\|([-\s]*)\|([-\s]*)\|([-\s]*)\|/g,
      '<table><thead><tr><th>$1</th><th>$2</th><th>$3</th><th>$4</th><th>$5</th></tr></thead><tbody>',
    )
    // 替换表格内容
    .replace(
      /\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|/g,
      '<tr><td>$1</td><td>$2</td><td>$3</td><td>$4</td><td>$5</td></tr>',
    )
    // 关闭表格标签
    .replace(/<\/tr>(?!.*<\/tr>)/s, '</tr></tbody></table>')
    // 替换标题
    .replace(/## (.*)/g, '<h2>$1</h2>')
    .replace(/\*\*(.*?):\*\* (.*)/g, '<div class="md-meta"><strong>$1:</strong> $2</div>')

  return html
})

// 转换为标准Markdown格式
const convertToMarkdown = () => {
  if (!sqlInput.value.trim()) {
    ElMessage.warning('请输入SQL语句')
    return
  }

  try {
    markdownResult.value = SqlToMarkdown.convert(sqlInput.value)
  } catch (error) {
    console.error('转换失败:', error)
    ElMessage.error('转换失败，请检查SQL语法')
  }
}

// 转换为自定义Markdown格式
const convertToCustomFormat = () => {
  if (!sqlInput.value.trim()) {
    ElMessage.warning('请输入SQL语句')
    return
  }

  try {
    markdownResult.value = SqlToMarkdown.convertCustomFormat(sqlInput.value)
  } catch (error) {
    console.error('转换失败:', error)
    ElMessage.error('转换失败，请检查SQL语法')
  }
}

// 复制到剪贴板
const copyToClipboard = () => {
  if (!markdownResult.value) return

  navigator.clipboard
    .writeText(markdownResult.value)
    .then(() => {
      ElMessage.success('已复制到剪贴板')
    })
    .catch((err) => {
      console.error('复制失败:', err)
      ElMessage.error('复制失败')
    })
}

// 清空所有内容
const clearAll = () => {
  sqlInput.value = ''
  markdownResult.value = ''
}

// 如果是模态窗口模式，自动初始化为可见
if (!props.isModal) {
  visible.value = true
}

// 导出方法供外部调用
defineExpose({
  openModal,
  closeModal,
})
</script>

<style scoped>
.sql-to-markdown-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.sql-to-markdown-container {
  width: 80%;
  height: 80vh;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  max-width: 1600px;
}

.sql-to-markdown-page {
  display: flex;
  justify-content: center;
  width: 100%;
}

.sql-to-markdown-content {
  width: 80%;
  max-width: 1600px;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial;
  overflow-y: auto;
  height: 100%;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #edf2f7;
}

.modal-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #9ca3af;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #ef4444;
}

.modal-content {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.sql-input,
.markdown-output {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  resize: vertical;
}

.buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.convert-btn,
.copy-btn,
.clear-btn {
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.convert-btn {
  background-color: #4f46e5;
  color: white;
}

.convert-btn:hover {
  background-color: #4338ca;
}

.convert-btn.custom {
  background-color: #10b981;
}

.convert-btn.custom:hover {
  background-color: #059669;
}

.clear-btn {
  background-color: #ef4444;
  color: white;
}

.clear-btn:hover {
  background-color: #dc2626;
}

.copy-btn {
  background-color: #6b7280;
  color: white;
  margin-top: 10px;
}

.copy-btn:hover {
  background-color: #4b5563;
}

.result-section {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.preview-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 6px;
}

h2 {
  color: #333;
  margin-bottom: 20px;
}

h3,
h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #1f2937;
}

.markdown-preview {
  overflow-x: auto;
}

.markdown-preview :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 15px;
}

.markdown-preview :deep(th),
.markdown-preview :deep(td) {
  border: 1px solid #e5e7eb;
  padding: 8px 12px;
  text-align: left;
}

.markdown-preview :deep(th) {
  background-color: #f3f4f6;
  font-weight: 600;
}

.markdown-preview :deep(tr:nth-child(even)) {
  background-color: #f9fafb;
}

.markdown-preview :deep(.md-meta) {
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .sql-to-markdown-container,
  .sql-to-markdown-content {
    width: 95%;
  }

  .sql-to-markdown-container {
    height: 90vh;
  }

  .buttons {
    flex-direction: column;
  }
}
</style>
